package com.ifonly.common.typeconverter.impl;

import com.ifonly.common.typeconverter.Converter;
import com.ifonly.common.typeconverter.TypeConversionException;
import com.ifonly.utils.ArrayUtils;

import java.sql.Clob;
import java.sql.SQLException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 21:36
 * @since JDK 1.6
 */
public class StringConverter implements Converter<String> {

    @Override
    public String convert(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof CharSequence) {	// for speed
            return value.toString();
        }
        Class type = value.getClass();
        if (type == Class.class) {
            return ((Class) value).getName();
        }
        if (type.isArray()) {
            if (type == char[].class) {
                char[] charArray = (char[]) value;
                return new String(charArray);
            }

            if (type == int[].class) {
                return ArrayUtils.toString((int[]) value);
            }
            if (type == long[].class) {
                return ArrayUtils.toString((long[]) value);
            }
            if (type == byte[].class) {
                return ArrayUtils.toString((byte[]) value);
            }
            if (type == float[].class) {
                return ArrayUtils.toString((float[]) value);
            }
            if (type == double[].class) {
                return ArrayUtils.toString((double[]) value);
            }
            if (type == short[].class) {
                return ArrayUtils.toString((short[]) value);
            }
            if (type == boolean[].class) {
                return ArrayUtils.toString((boolean[]) value);
            }
            return ArrayUtils.toString((Object[])value);
        }
        if (value instanceof Clob) {
            Clob clob = (Clob) value;
            try {
                long length = clob.length();
                if (length > Integer.MAX_VALUE) {
                    throw new TypeConversionException("Clob is too big.");
                }
                return clob.getSubString(1, (int) length);
            } catch (SQLException sex) {
                throw new TypeConversionException(value, sex);
            }
        }
        return value.toString();
    }

}
